package com.example.lotterysystem.service.activitystatus.operator;

import com.example.lotterysystem.dao.dataobject.ActivityDO;
import com.example.lotterysystem.dao.mapper.ActivityMapper;
import com.example.lotterysystem.dao.mapper.ActivityPrizeMapper;
import com.example.lotterysystem.service.dto.ConvertActivityStatusDTO;
import com.example.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import com.example.lotterysystem.service.enums.ActivityStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class ActivityOperator extends AbstractActivityOperator{
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Override
    public Integer sequence() {
        return 2;
    }

    /**
     * 活动状态是否需要转化
     * @param convertActivityStatusDTO
     * @return
     */
    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        Long activityId = convertActivityStatusDTO.getActivityId();
        ActivityStatusEnum targetActivityStatus = convertActivityStatusDTO.getTargetActivityStatus();
        // 活动 id 是否为空
        if (null == activityId
                || null == targetActivityStatus) {
            log.warn("needConvert 中 activityId 或 targetActivityStatus 为空");
            return false;
        }
        // 活动是否存在
        ActivityDO activityDO = activityMapper.selectById(activityId);
        if (null == activityDO) {
            log.warn("needConvert 中 {} 活动不存在", activityId);
            return false;
        }
        // 活动目标状态是否需要转换
        if (targetActivityStatus.name().
                equalsIgnoreCase(activityDO.getStatus())) {
            return false;
        }
        // 活动奖品是否已经抽完
        // 是否还存在状态为 INIT 的奖品
        int count = activityPrizeMapper.countPrize(activityId, ActivityPrizeStatusEnum.INIT.name());
        if (count > 0) {
            return false;
        }

        // 校验完成，需要进行状态转换
        return true;
    }

    /**
     * 转换活动状态
     * @param convertActivityStatusDTO
     * @return
     */
    @Override
    public Boolean convert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        try {
            log.info("活动 {} 状态转化", convertActivityStatusDTO.getActivityId());
            return activityMapper.updateStatus(convertActivityStatusDTO.getActivityId(),
                    ActivityStatusEnum.COMPLETED.name()) > 0;
        } catch (Exception e) {
            log.warn("convert 转化活动 {} 状态失败", convertActivityStatusDTO.getActivityId(), e);
            return false;
        }
    }
}
